<template>
  <div id="LabTMLBDict">
    <Breadcrumb content="样本类型" />
    <div class="bodyContent">
      <!-- vxe-toolbar -->
      <Splitpanes class="area">
        <Pane size="60">
          <vxe-toolbar perfect>
            <template #buttons>
              <!--              <el-select
                  v-model="form.orgId"
                  placeholder="请选择"
                  ref="selectOrgRef"
                  filterable
                  clearable
                  style="width: 200px; margin-right: 10px"
              >
                <el-option
                    hidden
                    :value="form.orgId ? form.orgId : ''"
                    :label="form.orgName"
                ></el-option>
                <el-tree
                    filterable
                    :data="orgList"
                    :props="defaultProps"
                    :expand-on-click-node="false"
                    :default-expand-all="true"
                    @node-click="handleOrgNodeClick"
                    highlight-current
                    ref="orgTreeRef"
                    node-key="id"
                    class="tools-tree"
                ></el-tree>
              </el-select>-->
              <vxe-input type="search" v-model="form.keyvalue" clearable class="vxeInputSearch" @search-click="findList" @clear="findList" @keyup.enter="findList" placeholder="关键字查询"></vxe-input>
              <vxe-button type="text" class="button-blue" @click="findList" icon="vxe-icon-refresh" :loading="loading">刷新</vxe-button>
              <vxe-button type="text" class="button-blue" @click="addSampleType" icon="vxe-icon-add">新增</vxe-button>
              <vxe-button type="text" class="button-blue" @click="syncData" icon="vxe-icon-lightning">同步数据</vxe-button>
              <vxe-button type="text" class="button-red" @click="deleteSampleType" icon="vxe-icon-delete">删除</vxe-button>
            </template>
          </vxe-toolbar>
          <div class="tableBox">
            <vxe-table ref="tableRef" border="inner" align="left" class="mytable-scrollbar" :loading="loading" height="auto" :data="tableData" :row-config="{ isCurrent: true }" :column-config="{ resizable: true }" show-overflow keep-source :scroll-y="{ enabled: true }" @current-change="tableCellClick" :menu-config="menuConfig" @menu-click="contextMenuClickEvent">
              <vxe-column type="checkbox" width="26"></vxe-column>
              <vxe-column type="seq" title="#" width="30"></vxe-column>
              <vxe-column field="sampleTypeCode" title="样本类型编码" width="120"> </vxe-column>
              <vxe-column field="sampleTypeName" title="样本类型名称" width="120"> </vxe-column>
              <vxe-column field="inputCode" title="助记符" width="90"> </vxe-column>
              <vxe-column field="orgName" title="组织机构" min-width="150"> </vxe-column>
            </vxe-table>
          </div>
        </Pane>
        <Pane size="40">
          <Splitpanes horizontal>
            <Pane size="100">
              <LabSampleTypeForm ref="LabSampleTypeFormRef" :currentRow="currentRow" @findListData="findList" />
            </Pane>
            <!-- <Pane size="55">
                <el-tabs type="border-card" style="height:100%;">
                  <el-tab-pane label="样本类型样本类型对照">
                  </el-tab-pane>
                </el-tabs>
              </Pane> -->
          </Splitpanes>
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>

<script lang="ts" setup>
// 引入组件区 ==========
import Breadcrumb from '@/components/Breadcrumb.vue'; //面包屑
import { reactive, ref, getCurrentInstance, onMounted } from 'vue';
import { Splitpanes, Pane } from 'splitpanes';
import { VXETable } from 'vxe-table';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import type { VxeTableInstance, VxeTablePropTypes, VxeTableEvents } from 'vxe-table';
import XEClipboard from 'xe-clipboard';
import LabSampleTypeForm from './LabSampleTypeForm.vue';
import { AppStore } from '@/stores/store';

// 全局变量定义区 ==========
let { proxy }: any = getCurrentInstance();
let store = AppStore();

const orgList = store.userInfo.orgList;
// 左侧表格:
const loading = ref(false); //刷新+表格加载
const form = reactive({
  keyvalue: '',
  orgId: store.userInfo.orgId,
  orgName: store.userInfo.orgName
}); //根据关键字查询
const tableRef = ref<VxeTableInstance<RowVO>>(); //表格ref标记
const tableData = reactive([]); //表格数据

// 右侧表单:
const LabSampleTypeFormRef = ref<InstanceType<typeof LabSampleTypeForm>>();
let currentRow: any = reactive({ id: '', code: '' });
let defaultProps = {
  children: 'children',
  label: 'name'
};

// vxe-table 表格右击属性
const menuConfig = reactive<VxeTablePropTypes.MenuConfig<RowVO>>({
  header: {
    options: [
      [
        { code: 'hideColumn', name: '隐藏列', disabled: false },
        { code: 'showAllColumn', name: '取消所有隐藏列', disabled: false }
      ]
    ]
  },
  body: {
    options: [
      [
        { code: 'copy', name: '复制', prefixIcon: 'vxe-icon-copy', disabled: false },
        { code: 'reload', name: '刷新', disabled: false },
        { code: 'remove', name: '删除', disabled: false },
        { code: 'save', name: '保存', prefixIcon: 'vxe-icon-save', disabled: false }
      ]
    ]
  },
  visibleMethod({ options, column }) {
    const isDisabled = !column;
    options.forEach((list) => {
      list.forEach((item) => {
        item.disabled = isDisabled;
      });
    });
    return true;
  }
});

// 方法定义区 =============
onMounted(() => {
  findList(); //获取样本类型表格数据
});

// 获取 样本类型表格数据
const findList = () => {
  loading.value = true;
  tableData.length = 0; //放入数据前清空数据
  const url = '/api/lab/labSampleType/findSampleTypeList';
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: { keyWords: form.keyvalue, orgId: form.orgId } })
    .then(async (res: any) => {
      tableData.push(...res.data);
      loading.value = false;
      if (res && res.data && res.data.length > 0) {
        tableCellClick({ row: res.data[0] });
        const $table = tableRef.value;
        if ($table) {
          //currentRow.id = '';
          await $table.setCurrentRow(res.data[0]);
        }
      }
    })
    .catch((err: any) => {
      loading.value = false;
      VxeMessage('获取样本类型列表数据异常', VxeNotifyType.error);
    });
};

function handleOrgNodeClick(data: any) {
  form.orgId = data.id;
  form.orgName = data.name;
  findList();
  const selectOrgRef: any = proxy.$refs['selectOrgRef'];
  selectOrgRef.blur();
}

// 新增样本类型
async function addSampleType() {
  (proxy.$refs.tableRef as any).clearCurrentRow();
  LabSampleTypeFormRef.value?.addNew((e) => {
    //todo
  });
}

//  保存样本类型
function saveSampleType() {
  LabSampleTypeFormRef.value?.saveForm((e) => {
    // findList();
  });
}

// 删除样本类型
async function deleteSampleType() {
  const arr = await tableRef.value?.getCheckboxRecords(true);
  if (!(arr && arr.length > 0 && arr[0])) {
    VxeMessage('请勾选要删除的样本类型', VxeNotifyType.info);
    return;
  } else if (arr.length > 1) {
    VxeMessage('一次只可选择删除一条数据', VxeNotifyType.info);
    return;
  } else {
    proxy
      .$confirm('确定删除选中数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(async () => {
        const url = '/api/lab/labSampleType/deleteSampleType';
        const arr = await tableRef.value?.getCheckboxRecords(true);
        if (arr && arr.length > 0 && arr[0]) {
          proxy.$http
            .post(url, arr[0])
            .then((res: any) => {
              if (res.status.code === 1) {
                VxeMessage('删除样本类型成功', VxeNotifyType.success);
                findList();
                LabSampleTypeFormRef.value?.clearFormData();
              } else {
                VxeMessage('删除样本类型失败', VxeNotifyType.error);
              }
            })
            .catch((err: any) => {
              // VxeMessage('删除样本类型异常', VxeNotifyType.error);
            });
        }
      });
  }
}

// 表格右击菜单项
const contextMenuClickEvent: VxeTableEvents.MenuClick<RowVO> = ({ menu, row, column }) => {
  const $table = tableRef.value;
  if ($table) {
    switch (menu.code) {
      case 'hideColumn':
        $table.hideColumn(column);
        break;
      case 'showAllColumn':
        $table.resetColumn(true);
        break;
      case 'copy':
        if (XEClipboard.copy((row as any)[column.field])) {
          VXETable.modal.message({ content: '已复制到剪贴板！', status: 'success' });
        }
        break;
      case 'reload':
        findList();
        break;
      case 'insertAt':
        $table.insertAt({}, row || -1).then(({ row }) => {
          $table.setEditCell(row, column || 'name');
        });
        break;
      case 'remove':
        $deleteSampleType();
        break;
      case 'save':
        saveSampleType();
        break;
    }
  }
};

// 表格选中当前行
function tableCellClick({ row }) {
  Object.assign(currentRow, row);
  proxy.$forceUpdate();
}
/**同步数据 */
function syncData() {
  const url = '/api/lab/labSampleType/syncSampleType';
  proxy.$http
    //注意此处的数据条数
    .get(url)
    .then(async (res: any) => {
      VxeMessage('同步数据完成', VxeNotifyType.success);
      findList();
    })
    .catch((err: any) => {
      VxeMessage('获取样本类型列表数据异常', VxeNotifyType.error);
    });
}
</script>
<style lang="scss" scoped>
#LabTMLBDict {
  width: 100%;
  height: 100%;
  .bodyContent {
    // 面包屑40px  上下间距10px
    height: calc(100% - 60px);
    .splitpanes {
      background-color: $base-white;
      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }
      .tableBox {
        height: calc(100% - 40px);
      }
    }
  }
}
</style>
